package com.example.bookmanagementsystem.service;

import com.example.bookmanagementsystem.entity.BookInfo;
import com.example.bookmanagementsystem.entity.PageRequest;
import com.example.bookmanagementsystem.entity.PageResult;
import com.example.bookmanagementsystem.enums.BookStatusEnum;
import com.example.bookmanagementsystem.mapper.BookInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class BookService {
    @Autowired
    private BookInfoMapper bookInfoMapper;

    /**
     * 根据页面来获取图书相关信息
     *
     * @param pageRequest
     * @return
     */
    public PageResult<BookInfo> getBookInfoByPage(PageRequest pageRequest) {
        if (pageRequest == null) {
            return null;
        }
        //获取图书的总数
        int bookCount = bookInfoMapper.countOfBook();
        //获取当前页面的记录
        List<BookInfo> bookInfos = bookInfoMapper.selectBookInfoByPage(pageRequest.getOffset(), pageRequest.getPageSize());
        if (bookInfos != null && !bookInfos.isEmpty()) {
            for (BookInfo bookInfo : bookInfos) {
                //根据status 获取状态的定义
                bookInfo.setStatusCN(BookStatusEnum.getNameByCode(bookInfo.getStatus()).getStatusName());
            }
        }
        return new PageResult<BookInfo>(bookInfos, bookCount, pageRequest);
    }

    /**
     * 根据传入的参数来添加新的图书
     *
     * @param bookInfo
     * @return
     */
    public Integer addBook(BookInfo bookInfo) {
        Integer result = 0;
        try {
            result = bookInfoMapper.insertBook(bookInfo);
        } catch (Exception e) {
            log.error("添加图书出错, e:{}", e);
        }
        return result;
    }

    /**
     * 根据id来查询对应图书的信息
     *
     * @param bookId
     * @return
     */
    public BookInfo getBookInfoById(Integer bookId) {
        return bookInfoMapper.selectBookInfoById(bookId);
    }

    /**
     * 根据传入的参数来更新的图书
     *
     * @param bookInfo
     * @return
     */
    public Integer updateBook(BookInfo bookInfo) {
        Integer result = 0;
        try {
            result = bookInfoMapper.updateBook(bookInfo);
        } catch (Exception e) {
            log.error("更新图书失败, e:{}", e);
        }
        return result;
    }

    /**
     * 根据传入的ids,批量的删除图书
     *
     * @param ids
     * @return
     */
    public Integer batchDelete(List<Integer> ids) {
        Integer result = 0;
        try {
            result = bookInfoMapper.batchDelete(ids);
        } catch (Exception e) {
            log.error("批量删除图书失败, ids:{}", ids);
        }
        return result;
    }
}
